<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<span>
				<el-cascader class="zs-select-md zs-space-right-sm" @change="cascaderChange" v-model="queryParams.inventoryClass" :options="cascaderData" :props="cascaderProps" clearable placeholder="清单分类" filterable />
				<el-input v-model="queryParams.inventoryName" class="zs-select-md zs-space-right-sm" placeholder="清单名称" clearable @blur="queryList" />
				<!-- <el-select v-model="queryParams.inventoryId" class="zs-select-md zs-space-right-sm" placeholder="清单名称" clearable filterable @change="queryList">
					<el-option v-for="item in inventoryList" :key="item.id" :label="item.name" :value="item.id" />
				</el-select> -->
				<el-input v-model="queryParams.deviceName" class="zs-select-md zs-space-right-sm" placeholder="设备名称" clearable @blur="queryList" />
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': queryParams.floorNum || queryParams.deviceStatusDict || queryParams.auditStatus || queryParams.deviceNum }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-input v-model="queryParams.deviceNum" class="zs-select-md zs-space-right-sm" placeholder="设备编号" clearable @blur="queryList" />
						<el-input v-model="queryParams.deviceBrand" class="zs-select-md zs-space-right-sm" placeholder="设备品牌" clearable @blur="queryList" />
						<el-select v-model="queryParams.floorNum" class="zs-select-md zs-space-right-sm" placeholder="楼层" clearable @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.BUILDING_LEVEL" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
						<el-select v-model="queryParams.deviceStatusDict" class="zs-select-md zs-space-right-sm zs-space-top" placeholder="设备状态" clearable @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.PROPERTY_DEVICE_STATUS" :key="item.id" :label="item.dictLabel" :value="item.id" />
						</el-select>
						<el-select v-model="queryParams.auditStatus" class="zs-select-md zs-space-right-sm zs-space-top" placeholder="审核状态" clearable @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.AUDIT_STATUS" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList" v-btnPermi="{ permis: ['p_btn_property_project_device_list_query'] }"> 查询 </el-button>
			</span>
			<span>
				<el-button class="zs-btn-plain zs-btn-md" @click="batchDownload">批量下载</el-button>
				<el-button class="zs-btn-plain zs-btn-md" v-btnPermi="{ permis: ['p_btn_property_project_device_list_export'], businessFlag: true }" @click="handleDownload(queryParams, equipmentExportApi, projectName + '设备')">
					<el-icon class="el-icon--left"> <Upload /> </el-icon>导出
				</el-button>
				<el-button class="zs-btn-plain zs-btn-md" v-btnPermi="{ permis: ['p_btn_property_project_device_list_import'], businessFlag: true }" @click="handleOpenImportDrawer()">
					<el-icon class="el-icon--left"> <Download /> </el-icon>导入
				</el-button>
				<el-button class="zs-btn-md zs-btn-primary" @click="openDrawer(false, 'add')" v-btnPermi="{ permis: ['p_btn_property_project_device_list_add'], businessFlag: true }">新增</el-button>
			</span>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column type="index" label="序号" width="60" align="center" :index="index => index + 1 + (tableData.currentPage - 1) * curPageSize" />
				<el-table-column prop="inventoryName" label="清单名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="deviceName" label="设备名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="deviceBrand" label="设备品牌" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="deviceSpecifications" label="设备规格" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="deviceNum" label="设备编号" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="floorNum" label="所在楼层" align="center" :formatter="defaultTableData" />
				<el-table-column prop="warrantyStatus" label="质保期" minWidth="120" align="center">
					<template #default="{ row }">
						<span :class="row.warrantyStatus == 1 ? 'zs-validata-status-yes' : 'zs-validata-status-no'">{{ row.warrantyStatus == 1 ? '质保期内' : '质保期外' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="lifeStatus" label="寿命期" minWidth="120" align="center">
					<template #default="{ row }">
						<span :class="row.lifeStatus == 1 ? 'zs-validata-status-yes' : 'zs-validata-status-no'">{{ row.lifeStatus == 1 ? '寿命期内' : '寿命期外' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="设备状态" width="120" align="center" :formatter="defaultTableData">
					<template #default="scope">
						<span>{{ getDicName('PROPERTY_DEVICE_STATUS', scope.row.deviceStatusDict) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="审核状态" width="120" align="center">
					<template #default="scope">
						<div :class="{ 'zs-approval-status-yes': scope.row.auditStatus == 1, 'zs-approval-status-no': scope.row.auditStatus == 0, 'zs-approval-status-wait': scope.row.auditStatus == null || scope.row.auditStatus == '' }">
							{{ getDictoryTxt('AUDIT_STATUS', scope.row.auditStatus) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="定义" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="openDrawer(true, 'info', row)" v-btnPermi="{ permis: ['p_btn_property_project_device_list_view'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="openDrawer(false, 'edit', row)" v-btnPermi="{ permis: ['p_btn_property_project_device_list_edit'], businessFlag: true }">编辑</el-button>
					</template>
				</el-table-column>
				<el-table-column label="二维码" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="qrCodeDownload(row)" v-btnPermi="{ permis: ['p_btn_property_project_device_list_qrcode_download'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="downloadFn(row)">下载</el-button>
					</template>
				</el-table-column>
				<!-- <el-table-column label="保养标准" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="goAcceptancePage(row, 'info')" v-btnPermi="{ permis: ['p_btn_property_project_device_list_as_view'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="goAcceptancePage(row, 'edit')" v-btnPermi="{ permis: ['p_btn_property_project_device_list_as_edit'], businessFlag: true }">配置</el-button>
					</template>
				</el-table-column> -->
				<el-table-column label="保养记录" width="90" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="goRecordPage(row, 'maintain')" v-btnPermi="{ permis: ['p_btn_property_project_device_list_maintainance_record'] }">{{ row.maintenanceNum + '条' }}</el-button>
					</template>
				</el-table-column>
				<el-table-column label="最近保养" width="150" align="left" :formatter="defaultTableData">
					<template #default="{ row }">
						{{ row.lastMaintenanceTime ? parseTime(row.lastMaintenanceTime, '{y}-{m}-{d} {h}:{i}') : '-' }}
					</template>
				</el-table-column>
				<el-table-column prop="formatBeforePresentDay" label="保养距今" align="left" width="120" :formatter="defaultTableData" />
				<el-table-column label="巡检记录" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="goRecordPage(row, 'check')" v-btnPermi="{ permis: ['p_btn_property_project_device_list_inspection_record'] }">{{ row.inspectionRecordNum + '条' }}</el-button>
					</template>
				</el-table-column>
				<el-table-column label="维修记录" width="90" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="goRepairPage(row)" disabled v-btnPermi="{ permis: ['p_btn_property_project_device_list_repair_record'] }">维修记录</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="level1Name" label="一级分类" minWidth="120" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="level2Name" label="二级分类" minWidth="120" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="level3Name" label="三级分类" minWidth="120" show-overflow-tooltip align="center" :formatter="defaultTableData" />
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>

	<!-- 设备抽屉 -->
	<DrawerBase ref="equipmentRef" :isShow="isShowDrawer" :isReadOnly="isReadOnly" :handleType="handleType" :currentEquipment="currentEquipment.data" @close="closeDrawer"> </DrawerBase>

	<!-- 二维码 -->
	<DialogQrCode ref="qrcodeRef" :currentRow="currentEquipment.data"></DialogQrCode>

	<!-- 导入 -->
	<hsImportData v-if="importDrawer.isShow" :isShow="importDrawer.isShow" @clickImportBtn="importFile($event, equipmentImportApi, route.query.projectCode, queryList)" @close="closeImportDrawer" @download="handleDownload({}, equipmentExportApi, projectName + '设备')"> </hsImportData>
</template>

<script setup>
	import DrawerBase from './components/drawerBase.vue';
	import DialogQrCode from './components/dialogQrCode.vue';
	import { getAllClassificationDataApi, getInventoryApi } from '@/api/common.js';
	import { equipmentListApi, equipmentExportApi, equipmentImportApi, batchDownloadApi } from '@/api/equipment.js';
	import { ref, reactive } from 'vue';
	import { useStore } from 'vuex';
	import { ElMessage } from 'element-plus';
	import { useRouter, useRoute } from 'vue-router';
	import { getDicName, defaultTableData, deepClone, getDictoryTxt, parseTime, monthDayDiff, downloadNewFile } from '@/utils/publicUtils';
	import useImportExport from '@/hooks/useImportExport';

	const { importDrawer, handleOpenImportDrawer, importFile, handleDownload, closeImportDrawer } = useImportExport();
	const router = useRouter();
	const route = useRoute();
	let store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);
	const projectName = ref(decodeURI(route.query.projectName));

	let dictObj = store.getters.getDictObj(['VALIDATE_FLAG', 'PROPERTY_DEVICE_STATUS', 'AUDIT_STATUS', 'BUILDING_LEVEL']);

	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	//查询条件
	let queryParams = reactive({ projectCode: route.query.projectCode, pageNumber: 1, pageSize: curPageSize.value, deviceNum: '', inventoryName: '', deviceName: '', deviceBrand: '', floorNum: '', deviceStatusDict: '', auditStatus: '1', inventoryClass: '' });

	// 级联规则
	const cascaderProps = reactive({
		checkStrictly: true,
		value: 'code',
		label: 'dictLabel',
	});
	// 级联数据
	let cascaderData = ref([]);
	// 级联变更
	const cascaderChange = val => {
		let cur = ['level1', 'level2', 'level3'];
		if (val) {
			cur.forEach((el, index) => {
				queryParams[el] = val[index] || '';
			});
			if (queryParams.level3) {
				getInventoryList();
			}
		} else {
			cur.forEach(ele => {
				queryParams[ele] = '';
			});
			inventoryList.value = [];
		}
		queryList();
	};
	//清单名称数据源
	let inventoryList = ref([]);
	const getInventoryList = async () => {
		let res = await getInventoryApi({
			classify1: queryParams.level1,
			classify2: queryParams.level2,
			classify3: queryParams.level3,
		});
		inventoryList.value = res.data.data;
	};

	// 抽屉相关
	let handleType = ref('');
	let isReadOnly = ref(false);
	let isShowDrawer = ref(false);
	let currentEquipment = reactive({ data: {} });
	const openDrawer = (flag, type, row) => {
		isReadOnly.value = flag;
		currentEquipment.data = row;
		isShowDrawer.value = true;
		handleType.value = type;
	};
	const closeDrawer = data => {
		isShowDrawer.value = data.isShow;
		data.isRefresh && queryList('init');
	};

	// 列表数据源
	const queryList = async init => {
		if (process.env.NODE_ENV !== 'development') {
			let portalResourceList = JSON.parse(localStorage.getItem('portalResourceList'));
			if (init != 'init' && !portalResourceList.includes('p_btn_property_project_device_list_query')) return;
		}
		tableData.loading = true;
		let res = await equipmentListApi(queryParams);
		if (res.data.code !== 200) return;
		initData(res.data.data.list);
		tableData.data = res.data.data.list || [];
		tableData.total = res.data.data.total || 0;
		tableData.loading = false;
	};

	const initData = list => {
		list.forEach(item => {
			let today = new Date();
			today.setHours(0, 0, 0, 0);
			let diffData = monthDayDiff(item.lastMaintenanceTime, today.getTime());
			let year = diffData.year ? diffData.year + '年' : '';
			let month = diffData.month ? diffData.month + '个月' : '';
			let day = diffData.day ? diffData.day + '天' : '';
			let diffDay = year + month + day;
			item.formatBeforePresentDay = item.lastMaintenanceTime ? diffDay : '-';
		});
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			queryParams.pageSize = size;
		} else {
			queryParams.pageNumber = size;
		}
		queryList('init');
	};

	//二维码
	const qrcodeRef = ref();
	const qrCodeDownload = async row => {
		if (!row.url) {
			ElMessage.warning('暂无二维码');
			return;
		}
		currentEquipment.data = row;
		qrcodeRef.value.dialogShow = true;
	};

	//二维码下载
	const downloadFn = async data => {
		if (!data.url) {
			ElMessage.warning('暂无二维码');
			return;
		}
		let splitList = data.url.split('.');
		let suffix = splitList[splitList.length - 1];
		const customName = `【${data.deviceName}】【${data.deviceNum}】.${suffix}`;
		fetch(data.url)
			.then(response => response.blob())
			.then(blob => {
				const a = document.createElement('a');
				a.href = URL.createObjectURL(blob);
				a.download = customName;
				a.click();
			})
			.catch(error => console.error('下载图片时出现错误：', error));
	};

	//二维码批量下载
	const batchDownload = async () => {
		let params = deepClone(queryParams)
		delete params.pageNumber
		delete params.pageSize
		batchDownloadApi(params).then(res => {
			downloadNewFile(res.data, `【${projectName.value}】设备二维码.zip`);
		});
	};

	// 获取全部分类数据
	const queryAllClassificationData = async () => {
		let res = await getAllClassificationDataApi();
		cascaderData.value = res.data.data || [];
	};

	//巡检|保养记录
	const goRecordPage = (row, type) => {
		let title = type == 'maintain' ? '保养' : '巡检';
		router.push({ path: '/page/routeController/index', query: { rid: 'recordMaintain', rTitle: title + '记录', id: row.id, pageType: 'equipment', funType: type } });
	};

	//维修记录
	const goRepairPage = row => {
		router.push({ path: '/page/routeController/index', query: { rid: '', rTitle: '维修记录' } });
	};

	//保养标准
	const goAcceptancePage = (row, pageType) => {
		// router.push({ name: 'EquipmentAcceptanceStandard', query: { rid: 'page_property_project_device_acceptance_standard_list', rTitle: '保养标准', eid: row.id, pageType: pageType } });
		router.push({ path: '/page/routeController/index', query: { rid: 'page_property_project_device_acceptance_standard_list', rTitle: '保养标准', eid: row.id, pageType: pageType } });
	};

	queryList('init');
	queryAllClassificationData();
</script>
